package com.cuit.qx.controller;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cuit.qx.aop.OperLog;
import com.cuit.qx.config.BasicData;
import com.cuit.qx.entity.Product;
import com.cuit.qx.service.ConfigService;
import com.cuit.qx.service.ProductService;
import com.cuit.qx.utils.Imagebase64;
import com.cuit.qx.utils.ReturnData;
import com.cuit.qx.utils.ReturnStateCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.util.Map;

/**
 * <p>
 * 产品
 * </p>
 *
 * @author lcj
 * @since 2021-11-23
 */
@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/api/product")
@Slf4j
public class ProductController {


    @Resource
    private ProductService productService;

    @Resource
    private ConfigService configService;

    @Resource
    private Imagebase64 imagebase64;

    /**
     * 产品列表查询
     *
     * @param map
     * @return
     */
    @PostMapping("/list")
    @OperLog(operModul = "产品信息", operType = "1", operDesc = "查询产品列表")
    public ReturnData list(@RequestBody Map<String, Object> map) {
        String startTime = (String) map.get("startTime");
        String endTime = (String) map.get("endTime");
        Integer type = (Integer) map.get("type");
        Integer pageNo = (Integer) map.get("pageNo");
        Integer pageSize = (Integer) map.get("pageSize");
        LambdaQueryWrapper<Product> queryWrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotBlank(startTime)) {
            queryWrapper.ge(Product::getCreateTime, startTime);
        }
        if (StrUtil.isNotBlank(endTime)) {
            queryWrapper.le(Product::getCreateTime, endTime);
        }
        if (type != null) {
            queryWrapper.eq(Product::getProductType, type);
        }
        queryWrapper.orderByDesc(Product::getCreateTime);
        pageNo = pageNo == null ? 1 : pageNo;
        pageSize = pageSize == null ? 10 : pageSize;
        Page<Product> page = new Page<>(pageNo, pageSize);
        IPage<Product> iPage = productService.page(page, queryWrapper);
        if (!iPage.getRecords().isEmpty()) {
            return new ReturnData(ReturnStateCode.SUCCEE, page, (int) iPage.getTotal());
        }
        return new ReturnData(ReturnStateCode.SUCCEEBUT);
    }

    @GetMapping("/getId/{id}")
    @OperLog(operModul = "产品信息", operType = "1", operDesc = "根据id查询产品信息")
    public ReturnData getById(@PathVariable(name = "id", required = true) String id) {
        Product byId;
        try {
            byId = productService.getById(id);
        } catch (Exception e) {
            return new ReturnData(ReturnStateCode.FAILED, e.getCause());
        }
        if (byId != null) {
            return new ReturnData(ReturnStateCode.SUCCEE, byId);
        }
        return new ReturnData(ReturnStateCode.SUCCEEBUT);
    }

    @DeleteMapping("/delete/{id}")
    @OperLog(operModul = "产品信息", operType = "4", operDesc = "根据id删除产品信息")
    public ReturnData deleteById(@PathVariable(name = "id", required = true) String id) {
        try {
            productService.removeById(id);
        } catch (Exception e) {
            return new ReturnData(ReturnStateCode.FAILED, e.getMessage());
        }
        return new ReturnData(ReturnStateCode.SUCCEE);
    }

    @GetMapping("/downLocal/{isOnLine}/{fileName:.+}")
    @OperLog(operModul = "产品信息", operType = "9", operDesc = "下载产品文件")
    public void downLocal(@PathVariable(value = "isOnLine") int isOnLine,
                          @PathVariable(value = "fileName") String fileName,
                          HttpServletRequest request,
                          HttpServletResponse response) {
        Map<String, Object> data = configService.getData();
        String path = data.get(BasicData.PROFILEPATH).toString();
        String filePath = path + File.separator + fileName;
        File file = new File(filePath);
        if (!file.exists()) {
            log.error("文件{}不存在！", fileName);
        }
        try {
            BufferedInputStream br = new BufferedInputStream(new FileInputStream(file.getPath()));
            byte[] buf = new byte[1024];
            int len = 0;
            response.reset();
            String name = new String(file.getName().getBytes("utf-8"), "ISO-8859-1");
            if (isOnLine == 1) { // 在线打开
                URL u = new URL("file:///" + file.getPath());
                response.setContentType(u.openConnection().getContentType());
                response.setHeader("Content-Disposition", "inline; filename=" + name);
            } else {
                response.setContentType("application/x-msdownload");
                response.setHeader("Content-Disposition", "attachment; filename=" + name);
                String origin = request.getHeader("Origin");
                response.setHeader("Access-Control-Allow-Origin", origin);
                response.setHeader("Access-Control-Allow-Credentials", "true");
                response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
            }
            request.getSession();
            OutputStream out = response.getOutputStream();
            while ((len = br.read(buf)) > 0)
                out.write(buf, 0, len);
            br.close();
            out.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/toImage")
    public ReturnData saveImages(@RequestBody Map<String,Object> map){
        String id = map.get("id").toString();
        String fileName = map.get("fileName").toString();
        String base64String = map.get("base64String").toString();
        Map<String, Object> data = configService.getData();
        String s = data.get(BasicData.IMAGESFILESAVEPATH).toString();
        File file = new File(s);
        if (!file.exists()){
            file.mkdirs();
        }
        String path = s+ File.separator+ fileName;
        imagebase64.base64StringToImage(path,base64String);
        return new ReturnData(ReturnStateCode.SUCCEE);
    }

    @RequestMapping("/getImages")
    public ReturnData getImages(){
        String imageBinary = imagebase64.getImageBinary();
        return new ReturnData(ReturnStateCode.SUCCEE,imageBinary);
    }
}

